import { makeGeometry } from '@/try-on/landmarks_helps'
import type { NormalizedLandmark } from '@mediapipe/tasks-vision'
import { Mesh, MeshNormalMaterial, type Scene } from 'three'
import type { Options } from '@/try-on/config'

export class FaceMesh {
  scene: Scene
  width: number
  height: number
  needUpdate = false
  material: MeshNormalMaterial
  faces?: Mesh
  landmark?: NormalizedLandmark[]
  options: Options
  constructor(scene: Scene, width: number, height: number, options: Options) {
    this.options = options
    this.scene = scene
    this.width = width
    this.height = height
    this.material = new MeshNormalMaterial({
      colorWrite: this.options.three.wireframe,
      wireframe: this.options.three.wireframe,
      wireframeLinewidth: 0.1,
    })
  }
  updateDimensions(width: number, height: number) {
    this.width = width
    this.height = height
    this.needUpdate = true
  }
  addFaces() {
    const geometry = makeGeometry(this.landmark!)
    this.faces = new Mesh(geometry, this.material)
    this.faces.name = 'faceMesh'
    this.faces.renderOrder = 2
    this.faces.position.set(0, 0, 0)
    this.faces.scale.set(this.width, this.height, this.width)
    this.scene.add(this.faces)
  }
  updateLandmarks(landmarks: NormalizedLandmark[]) {
    this.landmark = landmarks
    this.needUpdate = true
  }
  removeFaces() {
    this.scene.remove(this.faces!)
  }
  update() {
    if (this.needUpdate) {
      if (this.faces) {
        this.removeFaces()
      }
      if (this.landmark) {
        this.addFaces()
      }
      this.needUpdate = false
    }
  }
}
